import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import store from '@/store'
// import {Message, Loading} from 'element-ui'
import {Toast} from 'vant'
import {api_url, q_api_url, ERR_OK, dic_api_url} from "@/config/config";
import sign from "./sign";
// import { Loading } from 'element-ui';

// let loading = {close: new Function()};

const http = axios.create({
  baseURL: api_url,
  timeout: 50000,
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

// 添加请求拦截器
http.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  // loading = Loading.service({background: 'rgba(0, 0, 0, .6)'});
  let data = config.data || {};
  Object.keys(data).map(e => {
    // 去掉空的参数
    if (!data[e] && data[e] !== 0) {
      delete data[e];
    }
  });
  // 序列化data
  config.data = qs.stringify(data);
  return config;
}, error => {
  // 对请求错误做些什么
  throw error;
});

// 添加响应拦截器
http.interceptors.response.use(response => {
  // 对响应数据做点什么
  // loading.close();
  let data = response.data;
  try {
    data = sign.decode_post(data);
  } catch (e) {
  }
  if (data.code * 1 !== ERR_OK) throw data;
  return data.data || data.msg;
}, error => {
  // 对响应错误做点什么
  throw error;
});

http.$post = (url, params = {}, config = {}) => {
  // 字典接口
  sign.is_dictionary = false;
  let sendObj = config.sendObj;
  delete config.sendObj;
  let apiUrl = api_url;
  if (/(^\/?php\/dictionary)|(^\/?php\/api\/index\/login$)/i.test(url)) {
    // 词典相关接口配置
    apiUrl = dic_api_url;
    sign.is_dictionary = true;
    config = Object.assign(config, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'x-token': store.state.xToken.access_token
      }
    });
    // header['x-token'] = wx.getStorageSync('xtoken').access_token;
  }
  Object.keys(params).map(e => {
    // 去掉空的参数
    if (!params[e] && params[e] !== 0) {
      delete params[e];
    }
  });

  sign.params = params;
  let data = sign.encode_post();
  if (sendObj) {
    try {
      data = JSON.parse(data);
    } catch (e) {
    }
  }
  return axios.post(url, data, {
    baseURL: apiUrl,
    ...config,
  }).then(res => {
    let data = sign.decode_post(res.data);
    if (data.code * 1 === ERR_OK) return data.data || data.msg;
    throw data;
  });
};

http.testApi = (url, params = {}, needSign = false, config = {}) => {
  console.log(url, params);
  console.log(JSON.stringify(params));
  let api = needSign ? '$post' : 'post';
  return http[api](url, params, config).then(res => {
    console.log(JSON.stringify(res));
    console.log(res);
    return res;
  })
};

http.$get = (url, data = {}, to, needSign) => {
  Object.keys(data).map(e => {
    // 去掉空的参数
    if (!data[e] && data[e] !== 0) {
      delete data[e];
    }
  });
  if (needSign) {
    sign.params = data;
    data = JSON.parse(sign.encode_post());
  }
  let paramsStr = qs.stringify(data);
  paramsStr && (url += /\?/.test(url) ? '&' : '?');
  url = api_url + url + paramsStr;
  to && (location.href = url);
  return url;
};

http.upload = (url, params, config = {}) => {
  let form = new FormData();
  for (let k in params) {
    form.append(k, params[k]);
  }
  return axios.post(url, form, {
    baseURL: api_url,
    header: {'Content-Type': 'multipart/form-data'},
    ...config
  }).then(res => res.data);
};

http.qiniu = (file, callback = new Function()) => {
  http.get('Home/PadApp/GetUptoken?' + new Date().getTime()).then(({uptoken}) => {
    return axios.get(`http://uc.qbox.me/v1/query?ak=${uptoken.split(':')[0]}&bucket=pmworld`).then(res => {
      let form = new FormData();
      form.append('name', file.name);
      form.append('key', (e => {
        let s = 'app/a';
        let str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split('');
        for (let i = 0, len = str.length; i < 9; i++) {
          s += str[(Math.random() * 999 | 0) % len];
        }
        s += '_';
        s += (new Date().getTime() / 999) | 0;
        return s + e;
      })('.apk'));
      form.append('token', uptoken);
      form.append('file', file);
      return axios.post(res.data.http.up[1], form, {
        headers: {
          'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryYZaRCNXHInWklo3B'
        },
      }).then(data => {
        callback(data.data);
      }).catch(http.$err);
    }).catch(http.$err);
  }).catch(http.$err);
};

http.$err = err => {
  // loading.close();
  // 错误处理
  console.log(err);
  if (err.code) {
    Toast.fail(err.msg || err.data);
  } else {
    Toast.fail('网络错误！');
  }
};

Vue.prototype.axios = axios;
Vue.prototype.$err = http.$err;

export default http;
